package com.windchime.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Tag;
import com.windchime.blog.entity.vo.TagSearch;
import com.windchime.blog.mapper.TagMapper;
import com.windchime.blog.service.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author WindChime
 * @since 2021-08-02
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    /**
     * 保存标签
     * @param tag 标签
     * @return true
     */
    @Override
    public boolean saveTag(Tag tag) {
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.eq("name", tag.getName());
        Tag has_tag = baseMapper.selectOne(wrapper);
        if (has_tag == null) {
            return baseMapper.insert(tag) > 0;
        }
        return false;
    }

    /**
     * 分页查询带条件
     * @param page      当前页
     * @param limit     当前页条目数
     * @param tagSearch 条件
     * @return tags
     */
    @Override
    public PageInfo<Tag> selectTagList(Integer page, Integer limit, TagSearch tagSearch) {
        PageHelper.startPage(page, limit);
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (!StringUtils.isEmpty(tagSearch.getName())) {
            wrapper.like("name", tagSearch.getName());
        }
        List<Tag> tags = baseMapper.selectList(wrapper);
        return new PageInfo<>(tags);
    }

    /**
     * 修改标签
     * @param tag 标签
     * @return true
     */
    @Override
    public boolean editTag(Tag tag) {
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();

        wrapper.notIn("id", tag.getId());
        List<Tag> tags = baseMapper.selectList(wrapper);
        List<String> tagNames = tags.stream().map(Tag::getName).collect(Collectors.toList());

        if (!tagNames.contains(tag.getName())) {
            return baseMapper.updateById(tag) > 0;
        }

        return false;
    }
}
